package com.bee.beemanage.system.configs.SecurityConfigs;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bee.beemanage.api.entity.SysUser;
import com.bee.beemanage.api.entity.SysUserLogin;
import com.bee.beemanage.api.entity.output.LoginReturn;
import com.bee.beemanage.api.entity.token.TokenDetail;
import com.bee.beemanage.system.common.exceptions.LoginMaxLimitException;
import com.bee.beemanage.api.mapper.SysUserLoginMapper;
import com.bee.beemanage.api.service.SysUserService;
import com.bee.beemanage.system.common.utils.IpUtil;
import com.bee.beemanage.system.common.utils.redis.RedisUtils;
import com.bee.beemanage.system.common.utils.result.Result;
import com.bee.beemanage.system.common.utils.result.ResultCode;
import com.bee.beemanage.system.common.utils.result.ResultTool;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 陈国松
 * @createTime 2022/8/3 15:01
 * @description 账号登录成功的处理逻辑
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private SysUserService userService;

    @Resource
    private SysUserLoginMapper sysUserLoginMapper;
    @Resource
    private RedisUtils redisUtils;

    @Value("${token.expiredTime}")
    private int expiredTime;
    @Value("${bee.maxLoginDevice}")
    private int maxLoginDevice;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                        Authentication authentication) throws IOException {
        String requestURI = httpServletRequest.getRequestURI();
        //如果是浏览器管理端登录
        if("/admin/login".equals(requestURI)){
            System.out.println("管理端登录");
            loginSuccess(httpServletRequest,httpServletResponse,authentication);
        }else if("/admin/bee-manage/wx/login".equals(requestURI)){
            wxLoginSuccess(httpServletRequest,httpServletResponse,authentication);
        }

    }

    //管理端登录成功处理
    public void loginSuccess(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,Authentication authentication) throws IOException {
        //更新用户表上次登录时间、更新人、更新时间等字段
        SysUser userDetails = (SysUser) authentication.getPrincipal();
        SysUser user = userService.findUserByUserName(userDetails.getUsername());

        //进而前台动态的控制菜单的显示等，具体根据自己的业务需求进行扩展
        TokenDetail tokenDetail = new TokenDetail();
        StringBuffer as = new StringBuffer();
        for (GrantedAuthority authority : authentication.getAuthorities()) {
            as.append(authority.getAuthority())
                    .append(",");
        }
        tokenDetail.setAuthorities(as);
        tokenDetail.setUser(user);
        //查用户登录表
        QueryWrapper<SysUserLogin> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", user.getId());
        List<SysUserLogin> loginUser = sysUserLoginMapper.selectList(wrapper);
        String tokenKey = null;
        try {
            // 如果用户已经有了多个令牌且超出设定的最大值则报异常
            if (loginUser.size() >= maxLoginDevice) {
                throw new LoginMaxLimitException();
            } else {
                //否则颁发令牌
                tokenKey = loginInsert(tokenDetail, user,httpServletRequest);
            }
            LoginReturn loginReturn = new LoginReturn();
            loginReturn.setToken(tokenKey);
            //返回json数据
            Result result = ResultTool.success(loginReturn);
            //处理编码方式，防止中文乱码的情况
            httpServletResponse.setContentType("text/json;charset=utf-8");
            //塞到HttpServletResponse中返回给前台
            httpServletResponse.getWriter().write(JSON.toJSONString(result));
        } catch (LoginMaxLimitException | IOException e) {
            httpServletResponse.setContentType("text/json;charset=utf-8");
            httpServletResponse.getWriter().write(JSON.toJSONString(ResultTool.fail(ResultCode.USER_LOGIN_MAX_LIMIT)));
        }
    }

    /**
     * 微信小程序登录成功的处理逻辑
     * @param httpServletRequest
     * @param httpServletResponse
     * @param authentication
     */
    public void wxLoginSuccess(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,Authentication authentication){

    }
    private String loginInsert(TokenDetail tokenDetail, SysUser user, HttpServletRequest httpServletRequest) {
        //生成令牌
        String tokenKey = IdUtil.simpleUUID();
        //转字符串
        String value = JSON.toJSONString(tokenDetail);
        redisUtils.set("LoginUsers:" + tokenKey, value, expiredTime);
        //用户登录信息添加
        SysUserLogin sysUserLogin = new SysUserLogin();
        sysUserLogin.setUserId(user.getId());
        sysUserLogin.setUserName(user.getUsername());
        sysUserLogin.setIp(IpUtil.getIpAddr(httpServletRequest));
        sysUserLogin.setToken(tokenKey);
        sysUserLogin.setCreateUser(user.getId());
        sysUserLogin.setCreateTime(LocalDateTime.now());
        sysUserLoginMapper.insert(sysUserLogin);
        return tokenKey;
    }
}
